//
//  ReadAddDB.m
//  WYnewsss
//
//  Created by lanou on 16/4/28.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "ReadAddDB.h"
#import "UserInfoManager.h"
#define SQLITENAME           @"WYNews.sqlite" // 数据库名
#define READDETAILTABLE      @"ReadAdd" // 阅读详情数据表
@implementation ReadAddDB

-(id)init{
    self=[super init];
    if (self) {
        _dataBase=[DBManager defaultDBManager:SQLITENAME].dataBase;
    }
    return self;
}




//  创建数据表
- (void) createDataTable{
    FMResultSet *set =[_dataBase executeQuery:[NSString stringWithFormat:@"select count(*) from sqlite_master where type ='table' and name='%@'",READDETAILTABLE]];
    [set next];
    NSInteger count=[set intForColumnIndex:0];
    if (count) {
        NSLog(@"数据表已经存在");
    }else{
        //创建新的数据库
        NSString * sql = [NSString stringWithFormat:@"CREATE TABLE %@ (readID INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL, userID text, title text, tname text, imgsrc text)", READDETAILTABLE];
        BOOL res =[_dataBase executeUpdate:sql];
        if (!res) {
            NSLog(@"数据表创建成功");
        }else{
            NSLog(@"数据表创建失败");
        }
    }
}
//  插入一条数据
- (void) saveDetailModel:(ReadAddModel *)detailModel{
    //创建插入语句
    NSMutableString *query = [NSMutableString stringWithFormat:@"INSERT INTO %@ (userID title,tname,imgsrc) values (?,?,?)", READDETAILTABLE];
    NSLog(@"%@",query);
    //创建插入内容
    NSMutableArray *arguments =[NSMutableArray arrayWithCapacity:0];
    if (![[UserInfoManager getUserID] isEqualToString:@" "]) {
    if (detailModel.title) {
        [arguments addObject:detailModel.title];
    }
    if (detailModel.tname) {
        [arguments addObject:detailModel.tname];
    }if (detailModel.imgsrc) {
        [arguments addObject:detailModel.imgsrc];
    }
    NSLog(@"%@",query);
    NSLog(@"订阅一条数据");
    //执行
    [_dataBase executeUpdate:query withArgumentsInArray:arguments];
}
}
//  删除一条数据
- (void) deleteDetailWithTitle:(NSString *)detailTitle{
    NSString * query = [NSString stringWithFormat:@"DELETE FROM %@ WHERE title = '%@'", READDETAILTABLE, detailTitle];
    NSLog(@"删除成功");
    [_dataBase executeUpdate:query];
}
- (NSArray *)findWithUserID:(NSString *)userID{
    NSString * query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userID = '%@'", READDETAILTABLE, userID];
    FMResultSet * rs = [_dataBase executeQuery:query];
    NSMutableArray * array = [NSMutableArray arrayWithCapacity:[rs columnCount]];
    
    while ([rs next]) {
        ReadAddModel * detailModel = [[ReadAddModel alloc] init];
        detailModel.title = [rs stringForColumn:@"title"];
    detailModel.tname = [rs stringForColumn:@"tname"];
        detailModel.imgsrc = [rs stringForColumn:@"imgsrc"];
        [array addObject:detailModel];
    }
    [rs close];
    return array;
}

@end
